package ar.uba.fi.taller2.TreesWeb;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.util.Initiator;
import ar.uba.fi.taller2.TreesWeb.ui.Lookup;


public class Parameters {
	private  String path;
	private  String name;
	
	
	private static Parameters parametros =null;
	
	private Parameters() {
		//System.out.println("Working Directory = " + System.getProperty("user.dir"));
		this.setPath(System.getProperty("user.dir")+"/workspace/TressWeb/data/");
		this.setName("Parameters.dat");
	
	}
	
	
	
	
	
	public static Parameters getParametros(){
		if (parametros == null ) {
			parametros =new Parameters ();
		}
		return parametros;
	
	}
	
	public  void setMessage(String type,Integer clave,String dato){	
		this.writeFile(type,clave,dato);	
		
	}
	
	public  String getMessage(String type,Integer clave){
		String str=new String();
		str =readFile(type,clave);		
		return str.trim();
	}

	private String readFile(String type, Integer clave) {
			   // StringBuilder contents = new StringBuilder(); 
			    try {
			       BufferedReader input =  new BufferedReader(new FileReader(path+name));
			      try {
			        String line = null; 

			        while (( line = input.readLine()) != null){
			          if (line.contains(type+"\u0009"+clave.toString()))
			         return line.replaceAll(type+"\u0009"+clave.toString()+"\u0009", "");
			        }
			      }
			      finally {
			        input.close();
			      }
			    }
			    catch (IOException ex){
			      ex.printStackTrace();
			    }
			    
			  return "";
			  
		
	}

	private void writeFile(String type, Integer clave, String dato) {
		   // StringBuilder contents = new StringBuilder();
		    
		    try {
		       BufferedReader input =  new BufferedReader(new FileReader(path+name));
		       BufferedWriter output = new BufferedWriter(new FileWriter(path+name+".bak"));
		       Boolean encontrado=false;
		       String line = null; 
		      try {		        
		        while (( line = input.readLine()) != null){
		          if (line.contains(type+"\u0009"+clave.toString()))
		          {
		        	encontrado = true;
		        	output.write(type+"\u0009"+clave.toString()+"\u0009"+dato+"\n");
		          }
		          else
		        	  output.write(line+"\n");		          
		        }
		        if (!encontrado) output.write(type+"\u0009"+clave.toString()+"\u0009"+dato+"\n");
		      }
		      finally {
		        input.close();
		        output.close();
		        new File(path+name).delete();
		        new File(path+name+".bak").renameTo(new File(path+name));
		      }
		    }
		    catch (IOException ex){
		      ex.printStackTrace();
		    }
		    
		  	
	}
	
	public  String getPath() {
		return this.path;
	}

	public  void setPath(String path) {
		this.path = path;
	}

	public  String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	};
		
}
